package cn.edu.ecut.dao;

import cn.edu.ecut.entity.Option;
import cn.edu.ecut.entity.Topic;
import com.mozicoding.jdbc.DatabaseType;
import com.mozicoding.jdbc.JdbcHelper;
import com.mozicoding.jdbc.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class OptionDao {

    private static final String BASE_QUERY = "SELECT id , content , code , is_key , topic_id FROM t_options " ;

    private static final RowMapper<Option> mapper = new RowMapper<Option>() {
        @Override
        public Option wrap(ResultSet rs) throws SQLException {
            Option op = new Option();
            op.setId( rs.getInt( "id" ) );
            op.setContent( rs.getString( "content" ) );
            op.setCode( rs.getString( "code" ) );

            String isKey = rs.getString( "is_key" );
            if( "Y".equalsIgnoreCase( isKey ) ) {
                op.setKey( true );
            }

            int topicId = rs.getInt( "topic_id" );
            Topic t = new Topic();
            t.setId( topicId );
            op.setTopic( t );

            return op;
        }
    };

    public List<Option> findByTopicId( int topicId ){
        JdbcHelper h = JdbcHelper.getInstance( DatabaseType.MYSQL );
        String select = BASE_QUERY + " WHERE topic_id = ? " ;
        List<Option> optionList = h.list( select , mapper , topicId ) ;
        h.release();
        return optionList ;
    }

}
